unit KeyEdit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes,
  Graphics, Controls, Forms, Dialogs, StdCtrls,
  IOIRMain;

type
  TKeyEditForm = class(TForm)
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    Label4: TLabel;
    Address: TLabel;
    Value: TLabel;
    Name: TEdit;
    Keys: TEdit;
    OK: TButton;
    Cancel: TButton;
    ExtKey: TCheckBox;
    procedure FormKeyDown(Sender: TObject;
      var Key: Word; Shift: TShiftState);
    procedure ExtKeyClick(Sender: TObject);
  public
    KeyData: TKeyData;
    ShiftValue: TShiftState;
    procedure ShowKeyName;
  end;

implementation

{$R *.dfm}

// get the localized key description from the virtual key

procedure TKeyEditForm.ShowKeyName;

  function KeyName(Key: Word; Extended: Boolean): string;
  var
    ScanCode: Word;
    Buffer: array [0..255] of Char;
  begin
    // transform virtual key to scan code
    ScanCode := MapVirtualKey(Key, 0);
    if Extended then
      ScanCode := ScanCode + $100;
    // get localized key name
    GetKeyNameText(ScanCode shl 16, Buffer, SizeOf(Buffer));
    Result := Buffer;
  end;

begin
  Keys.Text := KeyName(KeyData.Key, ExtKey.Checked);
  // add modifier names
  if ssAlt in KeyData.Shift then
    Keys.Text := KeyName(VK_MENU, False) + '-' + Keys.Text;
  if ssCtrl in KeyData.Shift then
    Keys.Text := KeyName(VK_CONTROL, False) + '-' + Keys.Text;
  if ssShift in KeyData.Shift then
    Keys.Text := KeyName(VK_SHIFT, False) + '-' + Keys.Text;
end;

// the Keys edit carries the complete localized
// description of the key combination

procedure TKeyEditForm.FormKeyDown(Sender: TObject;
  var Key: Word; Shift: TShiftState);
begin
  // ignore if Key denotes a modifier key
  if (ActiveControl = Keys) and
   (Key <> VK_SHIFT) and (Key <> VK_CONTROL) and
   (Key <> VK_MENU) then
  begin
    // store the current key combination
    KeyData.Key   := Key;
    KeyData.Shift := Shift;
    ShowKeyName;
  end;
end;

// the extended bit (num pad vs normal key) is lost
// so we add it manually

procedure TKeyEditForm.ExtKeyClick(Sender: TObject);
begin
  KeyData.ExtendedKey := ExtKey.Checked;
  ShowKeyName;
end;

end.
